package com.yuexiao.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuexiao.config.RedisUtil;
import com.yuexiao.pojo.*;
import com.yuexiao.service.*;
import com.yuexiao.mapper.OrdersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @description 针对表【orders(订单表)】的数据库操作Service实现
 * @createDate 2022-08-10 14:10:57
 */
@Component
@Service(interfaceClass = OrdersService.class)
@Transactional(rollbackFor = Exception.class)
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders>
        implements OrdersService {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 新增一条订单记录
     *
     * @param orders Oders 订单实体对象
     * @return boolean true or false
     */
    @Override
    public Orders insertOrders(Orders orders) {

        //从redis中获取登录用户id
        Object loginId = redisUtil.get("loginId");
        if (loginId == null) {
            throw new RuntimeException("未登录");
        }

        //查询当前用户的购物车数据
        List<ShoppingCart> shoppingCartListByUserId = shoppingCartService.getShoppingCartListByUserId(Long.valueOf(String.valueOf(loginId)));
        if (shoppingCartListByUserId == null || shoppingCartListByUserId.size() == 0) {
            throw new RuntimeException("购物车为空,不能下单");
        }

        //查询用户数据
        User byId = userService.getById(Long.valueOf(String.valueOf(loginId)));

        //查询用户地址数据
        AddressBook addressBookById = addressBookService.getAddressBookById(orders.getAddressBookId());
        if (addressBookById == null) {
            throw new RuntimeException("用户地址信息有误,不能下单");
        }

        //生成订单号
        Long orderId = IdWorker.getId();

        AtomicInteger amount = new AtomicInteger(0);

        //组装订单明细信息
        List<OrderDetail> orderDetails = shoppingCartListByUserId.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());

        //组装订单数据
        orders.setId(orderId);
        orders.setOrderTime(new Date());
        orders.setCheckoutTime(new Date());
        orders.setStatus(2);
        orders.setAmount(new BigDecimal(amount.get()));
        orders.setUserId(Long.valueOf(String.valueOf(loginId)));
        orders.setConsignee(addressBookById.getConsignee());
        orders.setPhone(byId.getPhone());
        orders.setAddress((addressBookById.getProvinceName() == null ? "" : addressBookById.getProvinceName())
                + (addressBookById.getCityName() == null ? "" : addressBookById.getCityName())
                + (addressBookById.getDistrictName() == null ? "" : addressBookById.getDistrictName())
                + (addressBookById.getDetail() == null ? "" : addressBookById.getDetail()));

        //向订单表插入一条数据
        baseMapper.insert(orders);

        //向订单明细表插入多条数据
        orderDetailService.saveBatch(orderDetails);

        //清空购物车
        shoppingCartService.deleteShoppingCartByUserId(Long.valueOf(String.valueOf(loginId)));

        return orders;
    }


    /**
     * 分页查询用户订单信息
     *
     * @param uid      Long 用户id
     * @param page     int 当前页
     * @param pageSize int 每页显示条数
     * @return Page<Orders> 订单列表
     */
    @Override
    public Page<Orders> getOrdersByPage(Long uid, int page, int pageSize) {
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordersLambdaQueryWrapper.eq(Orders::getUserId,uid);
        Page<Orders> selectPage = baseMapper.selectPage(ordersPage, ordersLambdaQueryWrapper);

        //取出订单列表
        List<Orders> records = selectPage.getRecords();
        records=records.stream().map((item)->{
            List<OrderDetail> list = orderDetailService.list(new LambdaQueryWrapper<OrderDetail>().eq(OrderDetail::getOrderId, item.getId()));
            item.setOrderDetails(list);
            return item;
        }).collect(Collectors.toList());




        //将数据封装会page
        selectPage.setRecords(records);

        return selectPage;
    }
}




